import { defineStore } from 'pinia'
import { RouteRecordRaw } from 'vue-router'
import router,{ asyncRoutes } from '@/router'
interface State {
  isHandle: boolean,
  addRoutes: RouteRecordRaw[],
  firstRoute: string
}

type MyRoute = RouteRecordRaw & {
  meta?: {
    code?: string,
  }
}

//根据后台返回的菜单判断当前路由是否有权限
function hasPermission(route: MyRoute) {
  const permissionNameList = localStorage.getItem('permissionNameList')
  if (permissionNameList) {
    const pathList = JSON.parse(permissionNameList).map(item => item.name)
    if (route.meta && route.meta.code) {
      return pathList.includes(route.meta.code)
    }
  }
  return true
}

//过滤异步路由表，返回符合用户角色权限的路由表 
function filterAsyncRoutes(routes: MyRoute[]) {
  const ret: MyRoute[] = []
  routes.forEach(router => {
    const temp = { ...router }
    if (hasPermission(temp)) {
      ret.push(temp)
      if (temp.children) {
        temp.children = filterAsyncRoutes(temp.children)
      }
    }
  })
  return ret
}
//获取有权限的路由
function getFirstRoute(routes: MyRoute[]) : string{
  if (!routes.length || routes[0].path === '*') return ''
  let path = ''
  function getPath(route: MyRoute) {
    if (route.path.includes('/')) {
      path += route.path
    } else {
      path += '/' + route.path
    }
    if (route.children && route.children.length) {
      getPath(route.children[0])
    }
  }
  getPath(routes[0])
  return path
}
//过滤掉菜单children为0的路由
let maxLevel = -1
function filterAddRoutes(routes: RouteRecordRaw[]){
  for(let i = routes.length - 1; i >= 0; i--){
    if (!routes[i].children?.length  && !routes[i].component){
      routes.splice(i, 1)
    } else if (routes[i].children?.length){
      maxLevel++
      filterAddRoutes(routes[i].children ?? [])
    }
  }
}
export const usePermissionStore = defineStore('permission', {
  state: (): State => ({
    isHandle: false,
    addRoutes: [],
    firstRoute: ''
  }),
  actions: {
    setAsyncRoutes(dev = false){
      this.addRoutes = filterAsyncRoutes(asyncRoutes)
      filterAddRoutes(this.addRoutes)
      if(maxLevel > 1){
        switch(maxLevel){
        case 2:
          filterAddRoutes(this.addRoutes)
          break
        case 3:
          filterAddRoutes(this.addRoutes)
          filterAddRoutes(this.addRoutes)
          break
        case 4:
          filterAddRoutes(this.addRoutes)
          filterAddRoutes(this.addRoutes)
          filterAddRoutes(this.addRoutes)
          break
        }
      }
      if(dev){
        this.addRoutes = asyncRoutes
      }
      if(this.addRoutes.length){
        this.addRoutes.forEach(item => {
          router.addRoute(item)
        })
        // router.addRoute(this.addRoutes[0])
        this.isHandle = true
        this.firstRoute = getFirstRoute(this.addRoutes)
      }
      return this.addRoutes.length
    }
  }
})
